#include <iostream>
#include <stdlib.h>
#include "log/logfile.hxx"
#include "util/crc32.hxx"

int c = 0;

void printHeader(LogFileHeader& header) {
    std::cout<<"Header:"<<std::endl;
    std::cout<<header.toString()<<std::endl;
}

void printRecord(LogRecord& rec) {
    std::cout<<"Record: "<<c++<<std::endl;
    std::cout<<rec.toString()<<std::endl;
}

DbStatus printLog(uint32_t logId, const std::string& logPath) {
    DbStatus ret;

    LogFileReader reader(logId, logPath);

    ret = reader.init(); if(!ret.isok()) return ret;

    LogFileHeader header = reader.getHeader();
    printHeader(header);


    std::vector<LogRecord> records;
    ret = reader.getAllRecords(records);
    
    for(int i = 0; i < records.size(); ++i) {
        printRecord(records[i]);
    }

    return ret;
}

void usage() {
    std::cout<<"logprint -p <log home dir> -i <log file id>"<<std::endl;
    std::cout<<"options:"<<std::endl;
    std::cout<<"   -h"<<" help"<<std::endl;
    std::cout<<"   -p"<<" <log home dir> "<<std::endl;
    std::cout<<"   -i"<<" <log file id> "<<std::endl;
    exit(-1);
}

int main(int argc, char** argv) {
    int opt; extern char *optarg;
    int32_t logId = -1;
    std::string logPath;

    while ((opt = getopt(argc, argv, "p:i:h")) > 0) {
        switch(opt) {
            case 'p':
                logPath = optarg;
                break;
            case 'i':
                logId = atoi(optarg);
                break;
            case 'h':
            default:
                usage();
        }
    }

    if(logId < 0 || logPath.empty()) usage();

    CRC32::init(); 
    DbStatus ret = printLog(logId, logPath);
    if(!ret.isok()) std::cout<<ret.msg()<<std::endl;
}
